<template>
	<div class="search-suggestion">
		<van-cell
		
			icon="search"
			v-for="(text, index) in suggestions"
			:key="index"
      @click="$emit('search',text)"
		><div slot="title" v-html="highlight(text)"></div>
    </van-cell>
	</div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
	name: 'SearchSuggestion',
	components: {},
	props: {
		searchText: {
			type: String,
			required: true,
		},
	},
	data() {
		return {
			suggestions: [], //联想建议数据列表
		}
	},
	computed: {},
	watch: {
		searchText: {
			// handler(val) {
			// 	console.log(val)
			// 	this.loadSearchSuggestions(val)
			// },
      //防抖函数
			handler: debounce(function(val) {
				this.loadSearchSuggestions(val)
			}, 1000),
			immediate: true, //侦听开始立即调用（解决首次输入未侦听到的情况）
		},
	},
	created() {},
	mounted() {},
	methods: {
		async loadSearchSuggestions(q) {
			try {
				const { data } = await getSearchSuggestion(q)
				console.log(data)
				this.suggestions = data.data.options
			} catch (err) {
				console.log(err)
				this.$toast('数据获取失败，请稍后重试')
			}
		},
    highlight(text){
      const highlightStr=`<span style='color:red'>${this.searchText}</span>`
    const reg=new RegExp(this.searchText,'gi')
    return text.replace(reg,highlightStr)
    }
	},
}
</script>

<style scoped lang="less">

</style>
